<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Material Request</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
        }

        h1 {
            text-align: center;
            color: #333;
            margin-top: 30px;
        }

        form {
            background-color: #fff;
            max-width: 1200px;
            margin: 30px auto;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        label {
            display: block;
            margin-bottom: 5px;
            color: #555;
        }

        input[type="text"],
        input[type="number"],
        input[type="datetime-local"] {
            width: 40%;
            padding: 10px;
            margin-bottom: 15px;
            border: 1px solid #ccc;
            border-radius: 3px;
            box-sizing: border-box;
        }

        button {
            background-color: #007BFF;
            color: #fff;
            padding: 10px 20px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        button:hover {
            background-color: #0056b3;
        }

        a {
            display: block;
            text-align: center;
            color: #007BFF;
            text-decoration: none;
            margin-top: 10px;
        }

        a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <h1>Create Material Request</h1>
    <form id="material-request-form">
        <label for="request_id">Request ID:</label>
        <input type="number" id="request_id" name="request_id" required><br>
        <label for="user">User:</label>
        <input type="text" id="user" name="user" required><br>
        <label for="datetime">Datetime:</label>
        <input type="datetime-local" id="datetime" name="datetime" required><br>
        <h2>Material Counts</h2>
        <div id="material-counts">
            <!-- 初始的 Material Count -->
            <div class="material-count">
                <h3>领取单位</h3>
                <label for="address">地址:</label>
                <input type="text" id="address" name="addresses[]" required><br>
                <h4>物料单</h4>
                <div class="material-specifications">
                    <div class="material-specification">
                        <label for="spec_name">Name:</label>
                        <input type="text" id="spec_name" name="spec_names[0][]" required>
                        <label for="spec_count">Count:</label>
                        <input type="number" id="spec_count" name="spec_counts[0][]" required><br>
                    </div>
                </div>
                <button type="button" onclick="addSpecification(0)">Add Specification</button>
            </div>
        </div>
        <button type="button" onclick="addMaterialCount()">Add Material Count</button>
        <button type="button" onclick="submitForm()">Create</button>
    </form>
    <a href="/database">Back to Index</a>
    <script>
        let materialCountIndex = 1;
        function addMaterialCount() {
            const materialCounts = document.getElementById('material-counts');
            const newMaterialCount = document.createElement('div');
            newMaterialCount.classList.add('material-count');
            newMaterialCount.innerHTML = `
                <h3>Material Count</h3>
                <label for="address">Address:</label>
                <input type="text" id="address" name="addresses[]" required><br>
                <h4>Material Specifications</h4>
                <div class="material-specifications">
                    <div class="material-specification">
                        <label for="spec_name">Name:</label>
                        <input type="text" id="spec_name" name="spec_names[${materialCountIndex}][]" required><br>
                        <label for="spec_count">Count:</label>
                        <input type="number" id="spec_count" name="spec_counts[${materialCountIndex}][]" required><br>
                    </div>
                </div>
                <button type="button" onclick="addSpecification(${materialCountIndex})">Add Specification</button>
            `;
            materialCounts.appendChild(newMaterialCount);
            materialCountIndex++;
        }

        function addSpecification(materialCountIndex) {
            const materialSpecifications = document.querySelector(`.material-count:nth-child(${materialCountIndex + 1}) .material-specifications`);
            const newSpecification = document.createElement('div');
            newSpecification.classList.add('material-specification');
            newSpecification.innerHTML = `
                <label for="spec_name">Name:</label>
                <input type="text" id="spec_name" name="spec_names[${materialCountIndex}][]" required>
                <label for="spec_count">Count:</label>
                <input type="number" id="spec_count" name="spec_counts[${materialCountIndex}][]" required><br>
            `;
            materialSpecifications.appendChild(newSpecification);
        }

        function submitForm() {
            const form = document.getElementById('material-request-form');
            const formData = new FormData(form);
            const requestData = {
                request_id: parseInt(formData.get('request_id')),
                user: formData.get('user'),
                datetime: formData.get('datetime'),
                material_counts: []
            };

            const materialCounts = document.querySelectorAll('.material-count');
            materialCounts.forEach((count, index) => {
                const address = count.querySelector('input[name="addresses[]"]').value;
                const specifications = [];
                const specNames = count.querySelectorAll(`input[name="spec_names[${index}][]"]`);
                const specCounts = count.querySelectorAll(`input[name="spec_counts[${index}][]"]`);
                specNames.forEach((name, i) => {
                    specifications.push({
                        name: name.value,
                        count: parseInt(specCounts[i].value)
                    });
                });
                requestData.material_counts.push({
                    address: address,
                    specifications: specifications
                });
            });
            console.log(requestData);

            fetch('/create/material_request_item', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData)
            })
            .then(response => {
                if(response.redirected) {
                    window.location.href = response.url;
                }
            })
        //    .then(data => console.log(data))
           .catch(error => console.error('Error:', error));
        }
    </script>
</body>
</html>
